package org.example.httpFile;

import cn.hutool.core.lang.Console;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

// 简单的Netty客户端示例
public class NettyHTTPClient {
    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                     .channel(NioSocketChannel.class)
                     .handler(new ChannelInitializer<SocketChannel>() {
                         @Override
                         public void initChannel(SocketChannel ch) {
                             ch.pipeline().addLast(new HttpRequestDecoder()); // 解码器
                             ch.pipeline().addLast(new HttpRequestEncoder()); // 编码器
                             ch.pipeline().addLast(new SimpleChannelInboundHandler<FullHttpRequest>() {

                                 /**
                                  * Is called for each message of type {@link I}.
                                  *
                                  * @param ctx the {@link ChannelHandlerContext} which this {@link SimpleChannelInboundHandler}
                                  *            belongs to
                                  * @param msg the message to handle
                                  * @throws Exception is thrown if an error occurred
                                  */
                                 @Override
                                 protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
                                     Console.log(msg);
                                 }
                             });
                         }
                     });

            // 连接到服务器并发送消息
            Channel channel = bootstrap.connect("localhost", 8001).sync().channel();
            channel.writeAndFlush("Hello from Netty Client!");

            // 等待连接关闭
            channel.closeFuture().sync();
        } finally {
            // 关闭资源
            group.shutdownGracefully();
        }
    }
}